const { verify } = require("./jwt");
const { jwtSecret } = require("./config");
const UserServer = require("../servers/UserInfo");

module.exports = async (req, res, next) => {
  const token = req.headers["authorization"];
  // 从请求头获取 token 数据
  if (!token) {
    return res.status(401).end();
  }
  // 验证token是否有效
  try {
    const decodeToken = await verify(token, jwtSecret);
    console.log("===============decodeToken", decodeToken);
    const user = await UserServer.getAdminById(decodeToken.userId);
    console.log("===============user", user);
    req.user = user;
    next();
  } catch (err) {
    return res.status(401).end();
  }
    // 无效 -> 响应401
    // 有效 -> 把用户信息读取出来挂载到 req 请求对象上
    // 继续往后执行
};
